package com.monitor.zk.zookeeper.command;

import bean.ProjectInfo;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.text.StrSpliter;
import cn.hutool.core.util.StrUtil;
import com.monitor.zk.zookeeper.util.FormatSize;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
public class LinuxProjectInfoCommand extends AbstractExecCommand {

    public List<ProjectInfo> getProjectMonitor() throws IOException {
        List<ProjectInfo> projectInfoList = new ArrayList<>();
        String info = execCommand("top -b -n 1 | grep java");
        if(StrUtil.isEmpty(info)){
            return null;
        }
        List<String> list = StrSpliter.splitTrim(info, StrUtil.LF, true);
        for(String projectInfo : list){
            resolverProjectInfo(projectInfoList,projectInfo);
        }
        return projectInfoList;
    }

    protected void resolverProjectInfo(List<ProjectInfo> listInfos,String info){
        //PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
        //3582 root      20   0 3564544  98060  13292 S   0.0  2.5   1:20.08 java
        ProjectInfo projectInfo = new ProjectInfo();
        List<String> proInfos = StrSpliter.splitTrim(info,StrUtil.SPACE,true);
        projectInfo.setPid(Integer.parseInt(proInfos.get(0)));
        projectInfo.setUser(proInfos.get(1));
        projectInfo.setPr(proInfos.get(2));
        projectInfo.setNi(proInfos.get(3));
        projectInfo.setVirt(FormatSize.formSize(proInfos.get(4)));
        projectInfo.setRes(FormatSize.formSize(proInfos.get(5)));
        projectInfo.setShr(FormatSize.formSize(proInfos.get(6)));
        projectInfo.setStatus(formStatus(proInfos.get(7)));
        projectInfo.setCpu(proInfos.get(8)+"%");
        projectInfo.setMem(proInfos.get(9)+"%");
        projectInfo.setTime(proInfos.get(10).trim());
        projectInfo.setCommand(proInfos.get(11));
        projectInfo.setSearchTime(new Date());
        listInfos.add(projectInfo);
    }

    /**
     *
     * @param val
     * @return
     */
    private static String formStatus(String val) {
        String value = "未知";
        if ("S".equalsIgnoreCase(val)) {
            value = "睡眠";
        } else if ("R".equalsIgnoreCase(val)) {
            value = "运行";
        } else if ("T".equalsIgnoreCase(val)) {
            value = "跟踪/停止";
        } else if ("Z".equalsIgnoreCase(val)) {
            value = "僵尸进程 ";
        } else if ("D".equalsIgnoreCase(val)) {
            value = "不可中断的睡眠状态 ";
        } else if ("i".equalsIgnoreCase(val)) {
            value = "多线程 ";
        }
        return value;
    }
}
